package com.bj58.mis.bigdata.mdp.sys.service.impl;

import com.bj58.bsp.v2.Provider;
import com.bj58.bsp.v2.exception.BspException;
import com.bj58.bsp.v2.org.vo.Organization;
import com.bj58.bsp.v2.user.vo.Userinfo;
import com.bj58.mis.bigdata.mdp.sys.domain.Org;
import com.bj58.mis.bigdata.mdp.sys.service.DataSyncService;
import com.bj58.mis.bigdata.mdp.sys.service.OrgService;
import com.bj58.mis.bigdata.mdp.sys.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@Transactional
public class DataSyncServiceImpl implements DataSyncService {

    @Autowired
    private OrgService orgService;

    @Autowired
    private DataSyncMapper dataSyncMapper;

    @Override
    public void syncAll() {


        Long syncVersion = System.currentTimeMillis();
        // 同步机构
//        try {
//            for(int page=1, limit=500;;page++){
//                List<Organization> list = Provider.getOrgService().getOrgPageList(page, limit, null);
//                if(list==null){
//                    break;
//                }
//                syncOrgList(list, syncVersion);
//
//                if(list.size()<limit){
//                    break;
//                }
//            }
//        } catch (BspException e) {
//            throw new RuntimeException(e);
//        }

        // 同步用户
        try {
            for(int page=1, limit=500;;page++){
                List<Userinfo> list = Provider.getUserService().getUserPageList(page, limit, null);
                if(list==null){
                    break;
                }
                syncUserList(list, syncVersion);

                if(list.size()<limit){
                    break;
                }
            }
        } catch (BspException e) {
            throw new RuntimeException(e);
        }
    }

    private void syncOrgList(List<Organization> list, Long syncVersion){
        dataSyncMapper.saveOrgs(list, syncVersion);
//        List<Org> orgs = list.stream().map(item -> buildOrg(item, syncVersion)).collect(Collectors.toList());
//        orgService.saveAll(orgs);
    }
    private void syncUserList(List<Userinfo> list, Long syncVersion){
        dataSyncMapper.saveUsers(list, syncVersion);
    }

    private Org buildOrg(Organization item, Long syncVersion){
        Org org = new Org();

        org.setSyncVersion(syncVersion);

        org.setId(item.getId());
        org.setOrgName((item.getOrgName()));
        org.setDescription(item.getDescription());
        org.setLastUpdateTime(item.getLastUpdateTime());
        org.setParentId(item.getParentId201408());
        org.setParentPath(item.getParentPath201408());
        org.setLocation(item.getLocation());
        return org;
    }


    public static void main(String[] args) {
        DataSyncServiceImpl s = new DataSyncServiceImpl();
        s.syncAll();
    }

}
